Wire Expression2
Синтаксис --- кто хочет перевод всего (но корявый) тому => Сюда Синтаксис Expression 2 весьма изменился со времен прошлого Expression Chip, придется изучить немного больше команд, но это сделает ваши постройки намного более функциональными. Помните что как правило существует несколько способов написания кода, и задача может быть решена несколькими путями. : Отличия от Expression Gate Документация по Expression Gate 1 в основном подходит для Expression 2, самая главная разница между языками - конструкции if, которые вы могли увидеть выше. Исключая это, Expression 2 лучше во всех отношениях, а базовые основы кодинга такие же. В E2 также имеется хороший редактор кода с подсветкой синтаксиса! Сначала кода всегда идут строки с переменными, что похоже на Expression 1(хотя не то же самое) Переменные в expression должны быть объявлены до того как вы будете их использовать, так что раньше это выглядело подобным образом: N@variable example I@A B O@C D = A + B D >= 4 & A -> C = 1; D < 4 -> C = 0; а теперь: @name variable example @inputs A B @outputs C @persist D D = A + B if(D >= 4 & A) { C = 1 } else { C = 0 } Обратите внимание на линию @persist - здесь задаются переменные которые не должны фигурировать ни на входе ни на выходе. Причина подобной конструкции проста - в Expression 2 поддерживается много типов переменных. В Expression 1 это только номера и пакеты, а в Expression 2 поддерживается большое количество типов переменных, таких как strings(строковые переменные), vectors(векторы), и еще некоторые типы, и задание этих переменных в линию @persist заставляет компилятор отлавливать ошибки а не игнорировать их. Переменные В E2, все входы, выходы и переменные должны быть объявлены с заглавной буквы: : Выражение @trigger Выражение @trigger может выборочно разрешать и запрещать входам вызывать выполнение кода. Возможные значения: all/none, или список разрешенных входов @trigger all # всё по старому, изменение значения на входах всегда вызывает выполнение кода @trigger none # изменение значения на входах никогда не вызывает выполнение кода, его вызывает только таймер, и.т.п. функции @trigger Time Button # выполнение кода вызывается только при изменении значений на входах Time и Button Новые возможности @name vector example @inputs A:vector @outputs B:vector C = vec(0,0,0) if(A>C) { B = A:normalized() * 4 } else { B = C + A } Производительность Были проведены некоторые тесты в игре: ~3.000.000/сек арифметических операций (+-*/) на числах, 2000 операций, 200 выполнений за 0.13сек ~850.000/сек арифметических операций (+-*/) на векторах, 2000 операций, 100 выполнений за 0.23сек Горячие Клавиши Редактора Ctrl-Пробел Проверить (и переместить курсор на ошибку) Ctrl-S Сохранить Ctrl-Z Отменить Ctrl-Y Вернуть Ctrl-X Вырезать Ctrl-C Копировать Ctrl-V Вставить Ctrl-A Выделить Всё Ctrl-Up Прокрутить Вверх Ctrl-Down Прокрутить Вниз Ctrl-Left Прокрутить Влево Ctrl-Right Прокрутить Вправо Туториалы Если вы сделаете свой гайд по E2, пожалуйста добавьте его в этот список! Не забывайте про фидбэк(оставляйте там ссылочку на эту вики) *Expression 2 Guide *Expression 2 Examples *Русский сайт G-mod Expression2 *In-depth guide by Matte Category:Wire Addon Типы Expression2 использует несколько типов данных. По понятным причинам, тут только верхушка всего айсберга. : Числа Описание Производит операции над числами Комманды : Строки Описание Строки позволяют вам работать с текстом в E2. Необходимо для роты текстовых экранов. Пример работы *String Example by Hitman271 Комманды Create a string by wrapping the text in quotation marks, for example; "text goes here". Equal ( ) and Not equal (!=) operators are available, as is concatenation (+), for joining strings and numbers in any order. Concatenation returns a string. The first character of a string has the index 1. Negative indices are counted from the end of the string, with the last character being -1. Positive indices will be capped to the string's length. : Entity Description These entity functions allow you to get information from, and directly manipulate, entities in the game world (such as props). Entities can be found using many methods, from target finders, entity markers and even the expression itself with entity() from selfaware. Since the expression collects the data directly from the entity, it is much faster to handle calculations from within the E2 than having a beacon-sensor send its information to the gate. A valid entity will return true in an if-statement. This is helpful for preventing LUA errors resulting from using entity commands on entities which have been destroyed. Related Examples *RPM Counter by Beer *Remote Trail Maker (by OmicroN) 'Команды' Только операторы для объектов равны и не равны. Кроме того, объект будет возвращать Assigning one table variable to equal another will make them both refer to the same table. If you want to make a new copy of a table which will thereafter be set and retrieved from independently of the original table, you must use clone(). Related Examples *Table-RAM by Magos Mechanicus Commands In the interest of brevity, some commands which have many variants are shown as a pattern. may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push(*) can mean R:pushNumber(N), or R:pushString(S). : Array Thanks to: Erkle Description Same as table, but with much less memory footprint and is numerically indexed instead. It is similar to E1's packet support. Arrays can contain any datatype except table and array. Related Examples *Array-RAM by GUN Commands In the interest of brevity, some commands which have many variants are shown as a pattern. may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push(*) can mean R:pushNumber(N), or R:pushString(S). : Bone Developed by: TomyLobo Description This extension gives E2 support for bone entities. A bone can be any part of any ragdoll (head, left arm, right leg, etc). You can get a bone's position, orientation, velocity, etc, much like with regular props (although some things are missing). Array and table functions for bones are also provided. Related Examples Commands : Wirelink Description Wirelinks are an alternative to normal wires that offer a number of advantages. Any number of inputs or outputs on a component can be manipulated with one Wirelink, and you can also use it to retrieve the entity of a wirelinked component. Since all Wirelinks are capable of two-way communication, wirelinks are not clear-cut inputs or outputs. As such, to avoid ambiguity wirelinks which the expression should be able to manipulate are always declared in the @inputs of the expression. To connect this input to another component, you must use the Wirelink tool on the component to create a new output on it of the type Wirelink, then wire the input to the output as normal. Wirelink is not yet officially supported Related Examples *Wirelink Example by Hitman271 *Vector and Entity Wirelink Testing by fishface60 *Radar by Coder0xff Commands Equal and Not Equal operators are available. XWL here means the Wirelink input. : Complex Developed by: Fizyk Description Complex numbers are an extension of real numbers to include roots of negative numbers as well. Related Examples Commands : Basic extensions Core Description ... Commands : Self-Aware Description With entity() you can use Entity-Support to get all the data from the expression-entity. With concmd() you can execute console commands. hint() allows you to display strings quickly on your screen. Also, the chip has the ability to thrust itself. Beware of the interval you're choosing for your contraption, because of the time response. (The thrust lasts for 10ms) Related Examples *Using Hints *Beacon Sensor by Hitman271 *GPS by Fishface60 *Speedometer by integer *Gyroscope by GabbaGubbel Commands : Timer Description Timer functions are a way to trigger the expression to be run at a given time. Most interesting is the interval(N) function, that lets the expression be run continuously without needing triggering from inputs. Commands : Unit Conversion Description All conversions are precise so it is recommended to round the result if it is going to be displayed (round()). Related Examples *Speedometer by integer Commands : Units : : : Server Information Developed by: Beer Description The following functions allow you to get various information about the server, such as the current map name, gamemode, etc. Commands : * TIP: To get a list of all possible parameters for maxOfType(), open the console and type "find sbox_max". If you need "sbox_maxragdolls", you can simply pass "ragdolls" in the function. Constraint Developed by: ZeikJT Description The following functions get information about entities based on constraints Commands : : Chat Developed by: ZeikJT & Gwahir Description The following functions are for reading the chat log. This is similar to the text receiver. Related Examples *Chat Example by Matte Commands : Color Developed by: Jimlad Description These commands allow E2 to find the color of an entity and change it. Changing color only works on entities you own. Uses RGBA (Red, Green, Blue, Alpha) values, although when only RGB is specified, alpha will not be changed. Note that color values have a range of 0 - 255, where (0,0,0,255) is black, and (255,255,255,255) is white. Alpha is equivalent to opacity, where 0 is completely transparent and 255 is completely opaque. Commands : Advanced extensions Entity Discovery Developed by: Gwahir, TomyLobo Description Use these to find and filter entities. The basic find functions will return how many entities were found but the actual entities are stored on the chip until they are accessed using find(), findResult(N), or findClosest(V) There is a white list and a black list as well as functions for on the spot filtering and sorting White and black lists are always in effect and will be used automatically when you request a new list of entities. Control of the lists is achieved through the findAllow, Include, DisallowProp, Model, Class functions Exclude/Allow add/remove items from the black list while Include/Disallow do the same for the white list If the same object is covered by both the white list and the black list, the black list takes priority In the case of names, classes and models, partial strings are acceptable. Discovering entities is not cheap so suggested usage is to find what you're looking for an hold onto it in order to limit the number of queries you run. To prevent overuse of these features, two console variables have been included, wire_exp2_entFindRate and wire_exp2_playerFindRate. These are delays that control how often you can perform find queries, the ent variable is per chip, the player variable is for all chip owned by a specific player Related Examples *Thermometer Example by Entoros Commands : Global Variables Developed by: ZeikJT Description Global variables are a way to exchange data between two expression chips without the need for any wiring at all. The global variables will be sorted into groups so that you can avoid two chips overwriting each other's global data. By default a newly spawned chip will default to "default" as the group entry, but you can always change that by using the gSetGroup(s) function. Remember, all global variables persist until you delete them or you leave the server. They will never automatically reset. Using tables like this does isn't exactly a memory free deal, when using this on servers try to keep the amount of stored global variable at any one time down to a minimum. As of right now the global group will be reset after every run. Also, try to keep the group setting down to a minimum as it can be costly. Related Examples *Writing/Reading Global Variables by ZeikJT Commands : Built-In Ranger Developed by: ZeikJT Description The built-in ranger is heavily based on Erkle's original ranger. There are however some new functionalities that can be found in the commands below. Keep in mind that if you want to apply an option you must set it pre-ranging. This also introduces a new Variable type, the RD (defined as :ranger). It holds the data returned after a trace, you will need to use the trace data functions to retrieve useful data. These are to be used after you have done an actual trace. I will add a simple example to showcase the syntax and functionality. Related Examples *Using Built-In Ranger by ZeikJT *Radar by Coder0xff Commands : Sound Playback Developed by: ZeikJT Description Allows Expression 2 to play sounds. You can find a list of Half-life 2 sounds here or use GCFScape to preview each sound. The Duration is in seconds. If the sound is meant to be looped, set the duration to zero. If a sound is not designed to be looped (i.e: actor talking), it won't loop. The path must contain slashes '/' and not backslashes '\'. Commands : NPC control Developed by: Bobsymalone Description These functions allow you to control NPCs. You can create secondary AI systems responding to wire by telling NPCs how to feel about certain things, where to go, etc. You can also equip them with weapons. Related Examples *Wire_Expression2:Examples#NPC_pet_by_Bobsymalone Commands : Signals Developed by: Gwahir, TomyLobo Description These functions allow you to remotely execute exp2 chips, provided that chip is set to receive the given signal Scope Signals are restricted to certain scopes (only you, anyone, only others) (0,1,2) Simplified, true = anyone, false = only you. Scopes are used to restrict both who can receive your signal and who's signal you can receive. Scopes are always relative to the owner of the chip. So if player A sends to scope 1 and player B only receives from scope 0, he/she won't receive it, but player B will receive it with scopes 1 or 2 Group Set the chip's group with signalSetGroup(S) before calling the related runOnSignal, sendSignal, or signalSetOnRemove function The chip's signal group is always "default" at the start of every execution. runOnSignal() will subscribe to the given signal within the current group, this applies to sent signals as well. Any signal the chip receives will run the chip regardless of its current group (so long as it subscribed to the signal and group of the sent signal) A chip will never run because of a signal it sent itself. Signals are issued 10ms after the first unissued signal was sent. There can only ever be one unissued signal/group combination per receiver in each scope. Related Examples Commands : GLON Developed by: TomyLobo Description This extension allows you to serialize (=turn into a string) an array or table of values. Unsupported element types are: * Bone * some entity types (Vehicle, NPC, Weapon) * ranger data if the ranger was pointed at one of the entity types mentioned previously. Related Examples Commands : 3D Holograms Developed by: IamMcLovin & ZeikJT Description Adds the ability to project 3D objects. These objects can't be interacted with like most props; the only way to manipulate them is to use these functions. When using the holoCreate function, bear in mind that there is a delay associated with spawning holograms to avoid lagging servers. Avoid using holoCreate every execution. In general you should only ever use the holoCreate function once for each hologram in your code, for example by using the first() condition. Use the other functions like holoPos to update them thereafter. Note that except for wire_holograms_display_owners, all other console commands are useable by admins only! Console Variables : Related Examples Commands : : See Also *Expression 2 Formatting *Expression 2 Unofficial Addons *Expression 2 Bugs *Expression 2 Examples *Expression 2 Wishlist *Expression 2 Guide *How to write custom extensions *Wire_Expression2:Differences_to_Expression1 *Expression 2 syntax higlighting for Notepad++ *Wiremod Credits I would like to extend thanks to all of the following people who have made contributions to Expression 2 in one way or another, making it into what it is today. Shandolum, ZeikJT, Jimlad, Beer, Magos Mechanicus, Gwahir, chinoto, pl0x, Turck3, Ph3wl, Hunter234564, Fishface60, GUN, Bobsymalone, TomyLobo, Tolyzor, IamMcLovin, Fizyk And of course all you others out there who use it, provide constructive feedback or help others become familiar with it! Thank you! // Syranide P.S. I'm sorry if I forgot to mention someone! Category:Wire Addon Category:Wire Addon